package com.jxk.jms.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName : VerifyCodeFilter  //类名
 * @Description :   //描述
 * @Author : jxk  //作者
 * @Date: 2020-09-16 18:53  //时间
 */
@Component
public class VerifyCodeFilter extends GenericFilter {
    private String defaultFilterProcessUrl = "/login";

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        res.setContentType("application/json;charset=utf-8");
        if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
            // 验证码验证
            String requestCaptcha = request.getParameter("code");
            String genCaptcha = (String) request.getSession().getAttribute("index_code");
            if (StringUtils.isEmpty(genCaptcha)) {
                return;
            }
            if (StringUtils.isEmpty(requestCaptcha)) {
                response.setContentType("application/json;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.write("验证码不能为空");
                out.flush();
                out.close();
                return;
            }
            if (!genCaptcha.toLowerCase().equals(requestCaptcha.toLowerCase())) {
                response.setContentType("application/json;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.write("验证码错误");
                out.flush();
                out.close();
                return;
            }
        }
        chain.doFilter(request, response);
    }
}
